"""
行程提醒定时任务
"""
from celery import shared_task
from django.utils import timezone
from django.db.models import Q
from .models import ItineraryReminder
from apps.notifications.models import Notification
from utils.email_utils import send_reminder_email
import logging

logger = logging.getLogger(__name__)


@shared_task
def send_reminder_notifications():
    """
    发送待发送的提醒通知
    定时任务：每60秒执行一次
    """
    try:
        now = timezone.now()
        
        # 查找需要发送的提醒（已启用、待发送、时间已到）
        reminders = ItineraryReminder.objects.filter(
            is_enabled=True,
            status='pending',
            reminder_time__lte=now
        ).select_related('itinerary', 'itinerary__user')
        
        sent_count = 0
        for reminder in reminders:
            try:
                user = reminder.itinerary.user
                
                # 创建系统通知
                notification = Notification.objects.create(
                    user=user,
                    title=f'行程提醒：{reminder.itinerary.title}',
                    body=reminder.message or f'您的行程"{reminder.itinerary.title}"提醒时间已到',
                    type='reminder'
                )
                
                # 发送邮件提醒（如果用户已验证邮箱）
                if user.email_verified and user.email:
                    try:
                        send_reminder_email(user, reminder)
                    except Exception as email_error:
                        logger.warning(f'发送提醒邮件失败: {str(email_error)}')
                
                # 标记为已发送
                reminder.status = 'sent'
                reminder.sent_at = now
                reminder.save(update_fields=['status', 'sent_at'])
                
                sent_count += 1
                logger.info(
                    f'提醒已发送: 提醒ID={reminder.id}, '
                    f'行程={reminder.itinerary.title}, '
                    f'用户={user.username}'
                )
            except Exception as e:
                logger.error(f'发送提醒失败: 提醒ID={reminder.id}, 错误={str(e)}')
                # 标记为已取消（发送失败）
                reminder.status = 'cancelled'
                reminder.save(update_fields=['status'])
        
        if sent_count > 0:
            logger.info(f'本次任务发送了 {sent_count} 条提醒')
        
        return {
            'success': True,
            'sent_count': sent_count,
            'timestamp': now.isoformat()
        }
    except Exception as e:
        logger.error(f'发送提醒任务执行失败: {str(e)}')
        return {
            'success': False,
            'error': str(e),
            'timestamp': timezone.now().isoformat()
        }


@shared_task
def cleanup_old_reminders():
    """
    清理旧的已发送提醒（30天前）
    定时任务：每天执行一次
    """
    try:
        from datetime import timedelta
        
        cutoff_date = timezone.now() - timedelta(days=30)
        
        deleted_count = ItineraryReminder.objects.filter(
            status='sent',
            sent_at__lt=cutoff_date
        ).delete()[0]
        
        logger.info(f'清理了 {deleted_count} 条旧提醒')
        
        return {
            'success': True,
            'deleted_count': deleted_count,
            'timestamp': timezone.now().isoformat()
        }
    except Exception as e:
        logger.error(f'清理旧提醒任务执行失败: {str(e)}')
        return {
            'success': False,
            'error': str(e),
            'timestamp': timezone.now().isoformat()
        }

